<?php

namespace app\manage\corn;

use app\manage\model\admin\SysCrontab;
use buwang\service\CacheService;
use buwang\util\corn\MnCron;


/**
 * 定时任务
 * Class SystemCron
 */
class SystemCron extends MnCron
{
    /**
     * @param $event
     */
    public function handle($event): void
    {
        $this->corn_tick(1000, function () {
            $time = time();
            $list = CacheService::get('sys_crontab_key_mp', null);
            if (!$list) {
                $list = SysCrontab::where('is_open', 1)->select()->toArray();
                if ($list){
                    CacheService::set('sys_crontab_key_mp', $list);
                }
            }
            foreach ($list as $key => $item) {
                if ($item['is_open'] == 1) {
                    $data = $this->cornTimerCycleTime($item['type'], $item['cycle'], $time, $item['update_time']);
                    if ($time == $data['cycle_time']) {
                        $this->corn_after(1000, function () use ( $item, $time) {
                            // 更新最后执行时间
                            SysCrontab::where('id', $item['id'])->update([
                                'last_execution_time' => time(),
                                //'max_time' => $maxTime
                            ]);
                            $this->execute_cron($item);
                        });
                    }
                }
            }
        });
    }

    /**
     * 执行定时任务-需要自定义
     * @param $item
     * @return bool|void
     */
    public function execute_cron($item)
    {
        switch ($item['mark']) {
            case 'corn_test': //测试定时任务
                try {
                    //file_put_contents(root_path().'runtime/crontab.txt', date('Y-m-d H:i:s', time()) . '-' . "执行定时任务：{$item['name']}".PHP_EOL,FILE_APPEND);

                    return true;
                } catch (\Throwable $e) {
                    file_put_contents(root_path().'runtime/crontab.txt', date('Y-m-d H:i:s', time()) . '-' . "执行定时任务失败:". $e->getMessage().$e->getFile().$e->getLine().PHP_EOL,FILE_APPEND);
                }
                break;
        }
    }

    /**获取下次执行时间
     * @param $corn_type
     * @param $cycle
     * @param $time
     * @param $start_time
     * @return array
     */
    public function cornTimerCycleTime($corn_type, $cycle, $time, $start_time = 0)
    {
        if (!$time) $time = time();
        switch ($corn_type) {
            //定义N分钟
            case 1:
                $cycle_time = 60 * $cycle;
                $i = $time - $start_time;
                $more = $i % $cycle_time;
                if ($more == 0) {
                    $cycle_time = $time;
                } else {
                    $cycle_time = $time - $more + $cycle_time;
                }
                break;
            //定义N小时
            case 2:
                $arr = explode('/', $cycle);
                $todaystart = strtotime(date('Y-m-d H' . ':00:00', $time));
                $start_time = strtotime(date('Y-m-d H' . ':00:00', $start_time));
                $h = ($todaystart - $start_time) / 3600;
                $h = floor($h);
                $more = $h % $arr[0];
                if ($more == 0) {
                    $cycle_time = 60 * $arr[1];
                    $cycle_time = $todaystart + $cycle_time;
                    if ($cycle_time <= $time) {
                        $cycle_time = 60 * 60 * $arr[0] + 60 * $arr[1];
                    }
                } else {
                    $sh = $arr[0] - $more;
                    $cycle_time = 60 * 60 * $sh + 60 * $arr[1];
                }
                $cycle_time = $todaystart + $cycle_time;
                break;
            //定义每小时
            case 3:
                $cycle_time = strtotime(date('Y-m-d ' . 'H:' . $cycle . ':00', $time));
                break;
            //定义每天
            case 4:
                $arr = explode('/', $cycle);
                $cycle_time = strtotime(date('Y-m-d ' . $arr[0] . ':' . $arr[1] . ':00', $time));
                break;
            //定义N天
            case 5:
                $arr = explode('/', $cycle);
                $todaystart = strtotime(date('Y-m-d ' . '00:00:00', $time));
                $start_time = strtotime(date('Y-m-d ' . '00:00:00', $start_time));
                $d = ($todaystart - $start_time) / 86400;
                $d = floor($d);
                $more = $d % $arr[0];
                if ($more == 0) {
                    $cycle_time = 60 * 60 * $arr[1] + 60 * $arr[2];
                    $cycle_time = $todaystart + $cycle_time;
                    if ($cycle_time < $time) {
                        $cycle_time = 60 * 60 * 24 * $more + 60 * 60 * $arr[1] + 60 * $arr[2];
                    }
                } else {
                    $sd = $arr[0] - $more;
                    $cycle_time = 60 * 60 * 24 * $sd + 60 * 60 * $arr[1] + 60 * $arr[2];
                }
                $cycle_time = $todaystart + $cycle_time;
                break;
            //定义每星期
            case 6:
                $arr = explode('/', $cycle);
                $todaystart = strtotime(date('Y-m-d ' . '00:00:00', $time));
                $w = date("w");
                if ($w > $arr[0]) {
                    $d = 7 - $w + $arr[0];
                    $cycle_time = $todaystart + 60 * 60 * 24 * $d + 60 * 60 * $arr[1] + 60 * $arr[2];
                } else if ($w == $arr[0]) {
                    $to_time = 60 * 60 * $arr[1] + 60 * $arr[2];
                    $to_time = $todaystart + $to_time;
                    if ($time > $to_time) {
                        $d = 7 - $w + $arr[0];
                        $cycle_time = $todaystart + 60 * 60 * 24 * $d + 60 * 60 * $arr[1] + 60 * $arr[2];
                    } else {
                        $cycle_time = $to_time;
                    }
                } else {
                    $d = $arr[0] - $w;
                    $cycle_time = $todaystart + 60 * 60 * 24 * $d + 60 * 60 * $arr[1] + 60 * $arr[2];
                }
                break;
            //定义每月
            case 7:
                $arr = explode('/', $cycle);
                $current_d = date("d");
                $firstDate = date('Y-m-01', $time);
                $max_d = date('d', strtotime("$firstDate + 1 month -1 day"));
                $todaystart = strtotime(date('Y-m-d ' . '00:00:00', $time));
                if ($current_d > $arr[0]) {
                    $d = $max_d - $current_d + $arr[0];
                    $cycle_time = $todaystart + 60 * 60 * 24 * $d + 60 * 60 * $arr[1] + 60 * $arr[2];
                } elseif ($current_d == $arr[0]) {
                    $to_time = 60 * 60 * $arr[1] + 60 * $arr[2];
                    $to_time = $todaystart + $to_time;
                    if ($time > $to_time) {
                        $d = $max_d - $current_d + $arr[0];
                        $cycle_time = $todaystart + 60 * 60 * 24 * $d + 60 * 60 * $arr[1] + 60 * $arr[2];
                    } else {
                        $cycle_time = $to_time;
                    }
                } else {
                    $d = $arr[0] - $current_d;
                    $cycle_time = $todaystart + 60 * 60 * 24 * $d + 60 * 60 * $arr[1] + 60 * $arr[2];
                }
                break;
            //定义每年
            case 8:
                $arr = explode('/', $cycle);
                $cycle_time = strtotime(date('Y-' . $arr[0] . '-' . $arr[1] . ' ' . $arr[2] . ':' . $arr[3] . ':00', $time));
                break;
            default:
                $cycle_time = 0;
                break;
        }
        return ['cycle_time' => $cycle_time];
    }
}